package us.mmapp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import us.mmapp.util.ApplicationData;
import us.mmapp.util.DBOpenHelper;
import us.mmapp.util.FileNameUtil;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

public class HomeScreenActivity extends Activity
{
	public final static String PICTURE_LOCATION = Environment.getExternalStorageDirectory() + "/Media/Picture/";
	public final static String AUDIO_LOCATION = Environment.getExternalStorageDirectory() + "/Media/Audio/";
	public final static String VIDEO_LOCATION = Environment.getExternalStorageDirectory() + "/Media/Video/";
	public final static String THUMB_LOCATION = Environment.getExternalStorageDirectory() + "/Media/Thumbs/";
	File imageFile;
	final Context context = this;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		new File(AUDIO_LOCATION).mkdirs();
		new File(VIDEO_LOCATION).mkdirs();
		new File(PICTURE_LOCATION).mkdirs();
		new File(THUMB_LOCATION).mkdirs();
		ApplicationData.setContext(getApplicationContext());
	}

	@Override
	public void onResume()
	{
		super.onResume();
		ApplicationData.setContext(getApplicationContext());
		// Check if is logged in
		SharedPreferences settings = getSharedPreferences("LOGIN", 0);
		boolean isLoggedIn = settings.getBoolean("loggedIn", false);

		if (!isLoggedIn)
		{
			overridePendingTransition(R.anim.fade, R.anim.hold);
			startActivity(new Intent(this, LoginActivity.class));
		}
		else
		{
			if (ApplicationData.getIsLoggedIn() == false)
			{
				ApplicationData.logIn(settings.getString("password", ""),
							settings.getString("username", ""),
							settings.getLong("uid", -1));
			}
			GridView gridview = (GridView) findViewById(R.id.gridview);
			final Context context = this;
			gridview.setAdapter(new BaseAdapter()
			{
				// private Context mContext;

				public int getCount()
				{
					return 9;
				}

				public Object getItem(int position)
				{
					return null;
				}

				public long getItemId(int position)
				{
					return 0;
				}

				public View getView(int position, View convertView,
						ViewGroup parent)
				{
					if (convertView == null)
					{ // if it's not recycled, initialize some attributes

						LayoutInflater vi = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						convertView = vi.inflate(R.layout.gridview_item, null);
					}

					ImageView imageView = (ImageView) convertView.findViewById(R.id.griditem_icon);
					TextView textView = (TextView) convertView.findViewById(R.id.griditem_text);

					int resId = 0;
					String text = "";
					switch (position)
					{
					case 0:
						resId = R.drawable.map_icon;
						text = "View Map";
						break;
					case 1:
						resId = R.drawable.microphone_icon;
						text = "Record Audio";
						break;
					case 2:
						resId = R.drawable.camera_icon;
						text = "Take Picture";
						break;
					case 3:
						resId = R.drawable.video_icon;
						text = "Record Video";
						break;
					case 4:
						resId = R.drawable.folder_icon;
						text = "Manage Files";
						break;
					case 5:
						resId = R.drawable.friend_icon;
						text = "Manage Friends";
						break;
					case 6:
						resId = R.drawable.logout_icon;
						text = "Log off";
						break;
					case 7:
						resId = R.drawable.exit_icon;
						text = "Close";
						break;
					case 8:
						resId = R.drawable.refresh_icon;
						text = "Refresh";
						break;
					}

					imageView.setImageResource(resId);
					textView.setText(text);
					return convertView;
				}
			});

			gridview.setOnItemClickListener(new OnItemClickListener()
			{
				public void onItemClick(AdapterView<?> parent, View v, int position, long id)
				{
					// Map
					if (position == 0)
					{
						startActivity(new Intent(HomeScreenActivity.this, OnMapActivity.class));

					}
					// Audio
					else if (position == 1)
					{
						// startActivity(new Intent(HomeScreenActivity.this,
						// AudioActivity.class));
						startActivityForResult(new Intent(HomeScreenActivity.this, AudioActivity.class), 3);
					}
					// Picture
					else if (position == 2)
					{
						Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						imageFile = new File(FileNameUtil.getName(FileNameUtil.PICTURE));
						Uri uri = Uri.fromFile(imageFile);
						i.putExtra(MediaStore.EXTRA_OUTPUT, uri);
						startActivityForResult(i, 0);
					}
					// Video
					else if (position == 3)
					{
						Intent i = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
						startActivityForResult(i, 1);
					}
					// Manage
					else if (position == 4)
					{
						// int[] files=getLocalMedia();
						Intent intent = new Intent();
						intent.setClass(context, ManageMediaActivity.class);
						// Bundle bundle=new Bundle();
						// bundle.putIntArray("objectSID", files);
						// intent.putExtras(bundle);
						startActivity(intent);
					}
					// Friends
					else if (position == 5)
					{
						startActivity(new Intent(HomeScreenActivity.this, FriendsActivity.class));
					}
					// Log off
					else if (position == 6)
					{
						overridePendingTransition(R.anim.fade, R.anim.hold);
						startActivity(new Intent(HomeScreenActivity.this, LogoutActivity.class));
					}
					else if (position == 7)
					{
						finish();
					}
					else if (position == 8)
					{
						ApplicationData.refresh();
						
					}
				}
			});
			TextView tv = (TextView) findViewById(R.id.hello);
			tv.setText("Hello " + settings.getString("username", "") + "!");
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode != RESULT_OK)
			return;
		// Puts video into custom location

		if (requestCode == 1)
		{

			// *
			try
			{
				AssetFileDescriptor videoAsset = getContentResolver().openAssetFileDescriptor(data.getData(), "r");
				FileInputStream fis = videoAsset.createInputStream();
				imageFile = new File(FileNameUtil.getName(FileNameUtil.VIDEO));
				FileOutputStream fos = new FileOutputStream(imageFile);

				byte[] buf = new byte[1024];
				int len;
				while ((len = fis.read(buf)) > 0)
				{
					fos.write(buf, 0, len);
				}
				fis.close();
				fos.close();
			}
			catch (IOException io_e)
			{
				Log.e("VIDEO", io_e.getMessage());
			}
			// */
		}
		// Starts new activity to tag media
		Intent intent = new Intent();// intent is like the envelop
		intent.setClass(this, InfoActivity.class);// arg1 is the current class
													// and arg2 is the class u
													// wanna call
		Bundle bundle = new Bundle(); // bundle is like the letter
		bundle.putString("keyword", imageFile.toString());// arg1 is the keyword
															// of the txt, arg2
															// is the txt
		bundle.putBoolean("new", true);
		intent.putExtras(bundle);// actually it's bundle who carries the content
									// u wanna pass
		startActivity(intent);

	}

	public int[] getLocalMedia()
	{
		SharedPreferences settings = getSharedPreferences("LOGIN", 0);
		DBOpenHelper data = new DBOpenHelper(this, "mmAppDB", DBOpenHelper.VERSION);
		SQLiteDatabase db = data.getReadableDatabase();
		Cursor dbObjects = db.rawQuery("SELECT " + DBOpenHelper.SID + " FROM OBJECTS WHERE UID=" + settings.getLong("uid", 0), null);
		ArrayList<Integer> fullList = new ArrayList<Integer>();
		while (dbObjects.moveToNext())
		{
			fullList.add(new Integer(dbObjects.getInt(0)));
		}
		int[] fullList1 = new int[fullList.size()];
		for (int i = 0; i < fullList.size(); i++)
		{
			fullList1[i] = fullList.get(i).intValue();
		}
		dbObjects.close();
		db.close();
		return fullList1;
	}
}
